package com.boot.study.jianfan.domain;

import cn.hutool.core.lang.ObjectId;
import org.dromara.pdf.fop.doc.XEasyPdfTemplateDocument;
import org.dromara.pdf.fop.doc.page.XEasyPdfTemplatePage;
import org.dromara.pdf.fop.handler.XEasyPdfTemplateHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author lkz
 * @className ImageDownloadService
 * @description
 * @date 2024/3/14 15:37
 **/
public class ImageDownloadService {

    private static final String TEMP_FOLDER_NAME = "temp-images";

    public static void main(String[] args) throws IOException {
        String outPath = "D:\\pdf\\jianfan\\" + ObjectId.next() + ".pdf";
        ImageDownloadService downloadService = new ImageDownloadService();
        Path path = downloadService.downloadImageFromServer("https://medical.cdn.jianfancloud.com/edc/subject/visit/20231102_15_48_015门诊病历20231011.jpg");
        System.out.println(path.toFile().getPath());

        // 处理完成后删除临时文件夹及其内容
//        Files.walk(tempDirPath)
//                .sorted(Comparator.reverseOrder())
//                .map(Path::toFile)
//                .forEach(File::delete);
        XEasyPdfTemplateDocument document = XEasyPdfTemplateHandler.Document.build();
        XEasyPdfTemplatePage page = XEasyPdfTemplateHandler.Page.build();

        page.addBodyComponent(XEasyPdfTemplateHandler.Image.build().setHeight("100px").setWidth("100px").setPath(path.toFile().getPath()));
        document.addPage(page);

        document.transform(outPath);

    }

    public Path downloadImageFromServer(String serverImageUrl) throws IOException {
        // 获取临时文件夹路径
        Path tempFolderPath = createOrGetTempFolderPath();

        // 获取图片文件名
        String fileName = extractFileNameFromUrl(serverImageUrl);

        // 图片的临时存储路径
        Path tempFilePath = tempFolderPath.resolve(fileName);

        // 使用RestTemplate下载图片
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<byte[]> response = restTemplate.getForEntity(serverImageUrl, byte[].class);

        // 检查HTTP状态码
        HttpStatus statusCode = response.getStatusCode();
        if (!statusCode.is2xxSuccessful()) {
            throw new RuntimeException("Failed to download image, HTTP status code: " + statusCode);
        }

        // 将下载的图片内容写入临时文件
        Files.write(tempFilePath, response.getBody());

        return tempFilePath;
    }

    private Path createOrGetTempFolderPath() throws IOException {
        Path tempFolderPath = Paths.get(System.getProperty("java.io.tmpdir"), TEMP_FOLDER_NAME);
        if (!Files.exists(tempFolderPath)) {
            Files.createDirectory(tempFolderPath);
        }
        return tempFolderPath;
    }

    private String extractFileNameFromUrl(String imageUrl) {
        // 假设URL的最后一部分是文件名，可根据实际URL结构调整
        return imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
    }

    // 在业务逻辑完成后，可以调用以下方法删除临时文件夹及其内容
    public void cleanupTempFolder() throws IOException {
        Path tempFolderPath = Paths.get(System.getProperty("java.io.tmpdir"), TEMP_FOLDER_NAME);
        FileSystemUtils.deleteRecursively(tempFolderPath.toFile());
    }



}
